package com.taldh.algorithm.listnode;

import com.taldh.algorithm.base.ListNode;
import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class GetKthFromEnd {

    public ListNode getKthFromEnd(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        List<ListNode> nodes = new ArrayList<>();
        int length = 0;
        while (head != null) {
            length ++;
            nodes.add(head);
            head = head.next;
        }

        if (k > length) {
            return null;
        }

        return nodes.get(length - k);
    }

    public ListNode getKthFromEnd2(ListNode head, int k) {
        ListNode p=head;
        ListNode q=head;
        for(int i=0;i<k;i++){
            p=p.next;
        }
        while(p!=null){
            p=p.next;
            q=q.next;
        }
        return q;
    }

    @Test
    public void test() {
        Assert.assertEquals("[4, 5]",
                getKthFromEnd2(new ListNode(new int[]{1,2,3,4,5}) ,2).toString());
    }
}